package com.bjbn.tasks;

import com.bjbn.service.CsvReaderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CsvProcessingTask implements CommandLineRunner {

    @Autowired
    private CsvReaderService csvReaderService;

    private boolean hasStarted = false;

    @Override
    public void run(String... args) throws Exception {
        log.info("Application started. Loading CSV data and starting continuous processing...");
        // startContinuousProcessing();
    }

    @Scheduled(cron = "0 0 2 * * ?") // Run at 2 AM daily
    public void scheduledReload() {
        log.info("Scheduled CSV data reload started");
        // reloadData();
    }

    public void startContinuousProcessing() {
        if (hasStarted) {
            log.info("Continuous processing has already been started. Skipping...");
            return;
        }

        try {
            // Start continuous processing
            csvReaderService.startContinuousProcessing();
            hasStarted = true;
            log.info("Continuous processing started successfully");
        } catch (Exception e) {
            log.error("Error starting continuous processing: {}", e.getMessage(), e);
        }
    }

    public void stopContinuousProcessing() {
        csvReaderService.stopContinuousProcessing();
        hasStarted = false;
        log.info("Continuous processing stopped");
    }

    public void reloadData() {
        csvReaderService.reloadData();
        log.info("CSV data reloaded successfully");
    }

    public boolean isHasStarted() {
        return hasStarted;
    }

    public boolean isRunning() {
        return csvReaderService.isRunning();
    }
} 